<?php

class TranslationController extends Controller {

	/**
	 * @var string the default layout for the views.
	 * Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout = '//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters() {
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules() {
		return array(
			array('allow',
				'actions'=>array('index', 'view', 'create', 'ajax'),
				'users'=>array('*'),
			),
			array('allow',
				'actions'=>array('update'),
				'users'=>array('@'),
			),
			array('allow',
				'actions'=>array('admin', 'delete'),
				'users'=>array('admin'),
			),
			array('deny',
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id) {
		$this->render('view', array(
			'model'=>$this->loadModel($id),
		));
	}

	public function actionAjax() {
		$languageId = $_GET['languageId'];
		$dialect = $_GET['dialect'];
		$note = '';
		$author = '';

		if (isset($_POST['id']) && !empty($_POST['id'])) {
			$id = (int) strip_tags($_POST['id']);
		}

		if (isset($_POST['position']) && !empty($_POST['position'])) {
			$position = $_POST['position'];
		}

		if (isset($_POST['note']) && !empty($_POST['note'])) {
			$note = (string) strip_tags($_POST['note']);
		}

//		if (isset($_POST['link']) && !empty($_POST['link'])) {
//			$link = (string) strip_tags($_POST['link']);
//		}

		if (isset($_POST['author']) && !empty($_POST['author'])) {
			$author = (string) strip_tags($_POST['author']);
		}

		if (isset($_POST['get']) && !empty($_POST['get'])) {
			$result = $this->loadNotes($languageId, $dialect);
		}

		if (isset($_POST['add']) && !empty($_POST['add'])) {
			$result = $this->addNote(
				$languageId, $dialect, $position, $note, $author
			);
		}

		if (isset($_POST['delete']) && !empty($_POST['delete'])) {
			$result = $this->deleteNote($id);
		}

		if (isset($_POST['edit']) && !empty($_POST['edit'])) {
			$result = $this->editNote($id, $position, $note, $author);
		}

		echo json_encode($result);
		Yii::app()->end();
	}

	private function loadNotes($languageId, $dialect) {
		$condition = 'languageId = :languageId AND dialect = :dialect';
		$params = array(
			':languageId'=>$languageId,
			':dialect'=>$dialect,
		);
		$translations = Translation::model()->findAll($condition, $params);
		$notes = array();
		foreach ($translations as $translation) {
			$timestamp = strtotime($translation->createdAt);
			$notes[] = array(
				'ID'=>$translation->id,
				'LEFT'=>$translation->left,
				'TOP'=>$translation->top,
				'WIDTH'=>$translation->width,
				'HEIGHT'=>$translation->height,
				'DATE'=>array(
					'Y'=>date('Y', $timestamp),
					'M'=>date('m', $timestamp),
					'D'=>date('d', $timestamp),
					'H'=>date('H', $timestamp),
					'I'=>date('i', $timestamp),
				),
				'NOTE'=>$translation->value,
				'AUTHOR'=>$translation->humanName,
				'LINK'=>'',
			);
		}

		return $notes;
	}

	private function addNote($languageId, $dialect, $position, $note, $author) {
		if (!$note) return false;

		$positions = explode(',', $position);
		if (count($positions) != 4) return false;

		$model = new Translation;
		$model->left = $positions[0];
		$model->top = $positions[1];
		$model->width = $positions[2];
		$model->height = $positions[3];
		$model->value = $note;
		if (Yii::app()->user->isGuest) {
			$model->name = $author;
		} else {
			$model->userId = Yii::app()->user->id;
		}
		$model->dialect = $dialect;
		$model->languageId = $languageId;
		return $model->save();
	}

	private function editNote($id, $position, $note, $author) {
		$positions = explode(',', $position);
		if (count($positions) != 4) return false;

		$model = $this->loadModel($id);

		$model->left = $positions[0];
		$model->top = $positions[1];
		$model->width = $positions[2];
		$model->height = $positions[3];
		$saved = true;
		$transaction = $model->dbConnection->beginTransaction();
		if ($model->value != $note) {
			$history = new History;
			$history->translationId = $model->id;
			$history->value = $model->value;
			$history->userId = $model->userId;
			$history->name = $model->name;
			$saved = $history->save() && $saved;
			$model->value = $note;
			if (Yii::app()->user->isGuest) {
				$model->name = $author;
			} else {
				$model->userId = Yii::app()->user->id;
			}
		}
		$saved = $model->save() && $saved;
		if ($saved) {
			$transaction->commit();
		} else {
			$transaction->rollBack();
		}
		return $saved;
	}
	
	private function deleteNote($id) {
		$translation = Translation::model();
		$transaction = $translation->dbConnection->beginTransaction();
		$condition = 'translationId = :translationId';
		$params = array(':translationId'=>$id);
		$deleted = History::model()->deleteAll($condition, $params);
		$deleted = Translation::model()->deleteByPk($id) && $deleted;
		if ($deleted) {
			$transaction->commit();
		} else {
			$transaction->rollBack();
		}
		return $deleted;
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate() {
		$this->layout = 'column1';

		$model = new Translation;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if (isset($_POST['Translation'])) {
			$model->attributes = $_POST['Translation'];
			if ($model->save()) $this->redirect(array('view', 'id'=>$model->id));
		}

		$language = $this->loadLanguageModel($_GET['languageId']);
		$model->dialect = $_GET['dialect'];

		$navList = Language::createList($language->page->chapterId);
		$data = array(
			'model'=>$model,
			'navList'=>$navList,
			'language'=>$language,
		);
		$this->render('create', $data);
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id) {
		$model = $this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if (isset($_POST['Translation'])) {
			$model->attributes = $_POST['Translation'];
			if ($model->save()) $this->redirect(array('view', 'id'=>$model->id));
		}

		$this->render('update', array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id) {
		if (Yii::app()->request->isPostRequest) {
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if (!isset($_GET['ajax']))
					$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
				throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex() {
		$dataProvider = new CActiveDataProvider('Translation');
		$this->render('index', array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin() {
		$model = new Translation('search');
		$model->unsetAttributes();  // clear any default values
		if (isset($_GET['Translation'])) $model->attributes = $_GET['Translation'];

		$this->render('admin', array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id) {
		$model = Translation::model()->findByPk($id);
		if ($model === null)
				throw new CHttpException(404, 'The requested page does not exist.');
		return $model;
	}

	public function loadLanguageModel($id) {
		$model = Language::model()->findByPk($id);
		if ($model === null) {
			throw new CHttpException(404, 'The requested page does not exist.');
		}
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model) {
		if (isset($_POST['ajax']) && $_POST['ajax'] === 'translation-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

}
